local extension = Package("joy_ccxh")
extension.extensionName = "joy"

Fk:loadTranslationTable{
  ["joy_ccxh"] = "欢乐-璀璨星河",
}

local U = require "packages/utility/utility"

local dufuren = General(extension, "joy__dufuren", "wei", 3, 3, General.Female)
local yise = fk.CreateTriggerSkill{
  name = "joy__yise",
  anim_type = "control",
  events = {fk.AfterCardsMove},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      for _, move in ipairs(data) do
        if move.from == player.id and move.to and move.to ~= player.id and move.toArea == Card.PlayerHand then
          self.yise_to = move.to
          for _, info in ipairs(move.moveInfo) do
            self.yise_color = Fk:getCardById(info.cardId).color
              return true
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if self.yise_color == Card.Red then
      return player.room:askForSkillInvoke(player, self.name, data, "#joy__yise-invoke1::"..self.yise_to)
    else
      return player.room:askForSkillInvoke(player, self.name, data, "#joy__yise-invoke3::"..self.yise_to)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.yise_to)
    if self.yise_color == Card.Red then
      local choices = {"joy__yiseDrawCard","joy__yisecancel"}
      if to:isWounded() then
        table.insert(choices,"joy__yiseCover")
      end
      local choice = player.room:askForChoice(player,choices,self.name)
      if choice == "joy__yiseDrawCard" and not player.dead then
        player:drawCards(1,self.name)
      elseif choice == "joy__yiseCover" then
        room:recover({
          who = to,
          num = 1,
          recoverBy = player,
          skillName = self.name
        })
      else
        return
      end
    elseif self.yise_color == Card.Black then
      room:addPlayerMark(to, "@joy__yise", 1)
    end
  end,
}
local yise_delay = fk.CreateTriggerSkill{
  name = "#joy__yise_delay",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:getMark("@joy__yise") > 0 and data.card and data.card.trueName == "slash"
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage + player:getMark("@joy__yise")
    player.room:setPlayerMark(player, "@joy__yise", 0)
  end,
}
local shunshi = fk.CreateTriggerSkill{
  name = "joy__shunshi",
  anim_type = "control",
  events = {fk.EventPhaseStart, fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.EventPhaseStart and not player:isNude() then
        return player.phase == Player.Start
      elseif event == fk.Damaged and not player:isNude() and player.room.current ~= player  then
        return true
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = {}
    for _, p in ipairs(room:getOtherPlayers(player)) do
        table.insert(targets, p.id)
    end
    local tos, id = room:askForChooseCardAndPlayers(player, targets, 1, 1, ".", "#shunshi-cost", self.name, true)
    if #tos > 0 then
      self.cost_data = {tos[1], id}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
      room:obtainCard(self.cost_data[1], self.cost_data[2], false, fk.ReasonGive)
      room:addPlayerMark(player, "@joy__shunshi_drawcards", 1)
      room:addPlayerMark(player, "@joy__shunshi_slash", 1)
      room:addPlayerMark(player, "@joy__shunshi_maxcard", 1)
  end,

  refresh_events = { fk.EventPhaseEnd },
  can_refresh = function(self, event, target, player, data)
      return (player.phase == Player.Play and player:getMark("@joy__shunshi_slash") ~= 0) or (player.phase == Player.Discard and player:getMark("@joy__shunshi_maxcard") ~= 0)
  end,
  on_refresh = function(self, event, target, player, data)
    if player.phase == Player.Play then
      player.room:setPlayerMark(player, "@joy__shunshi_slash", 0)
    elseif player.phase == Player.Discard then
      player.room:setPlayerMark(player, "@joy__shunshi_maxcard", 0)
    end
  end,

}
local shunshi_delay = fk.CreateTriggerSkill{
  name = "#joy__shunshi_delay",
  mute = true,
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:getMark("@joy__shunshi_drawcards") > 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    data.n = data.n + player:getMark("@joy__shunshi_drawcards")
    player.room:setPlayerMark(player, "@joy__shunshi_drawcards", 0)
  end,
}
local shunshi_targetmod = fk.CreateTargetModSkill{
  name = "#joy__shunshi_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and scope == Player.HistoryPhase then
      return player:getMark("@joy__shunshi_slash")
    end
  end,
}
local shunshi_maxcards = fk.CreateMaxCardsSkill{
  name = "#joy__shunshi_maxcards",
  correct_func = function(self, player)
    return player:getMark("@joy__shunshi_maxcard")
  end,
}

local shunshi_armor = fk.CreateTriggerSkill{
  name = "#joy__shunshi_armor",
  mute = true,
  main_skill = shunshi,
  events = {fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill("joy__shunshi") and player.phase == Player.Play and player:getMark("@joy__shunshi_slash") > 0 then
      return data.card.trueName == "slash" 
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local card_event = room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
    card_event.joy__shunshi_armor = true
    for _, p in ipairs(room.alive_players) do
      room:addPlayerMark(p, fk.MarkArmorNullified)
    end
end,

refresh_events = {fk.CardUseFinished},
can_refresh = function(self, event, target, player, data)
  if player ~= target then return false end
  local card_event = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard, true)
  return card_event and card_event.joy__shunshi_armor
end,
on_refresh = function(self, event, target, player, data)
  local room = player.room
  for _, p in ipairs(room.alive_players) do
    room:removePlayerMark(p, fk.MarkArmorNullified)
  end
end,
}
yise:addRelatedSkill(yise_delay)
shunshi:addRelatedSkill(shunshi_delay)
shunshi:addRelatedSkill(shunshi_targetmod)
shunshi:addRelatedSkill(shunshi_maxcards)
shunshi:addRelatedSkill(shunshi_armor)
dufuren:addSkill(yise)
dufuren:addSkill(shunshi)
Fk:loadTranslationTable{
  ["joy__dufuren"] = "杜夫人",
  ["#joy__dufuren"] = "沛王太妃",

  ["joy__yise"] = "异色",
  [":joy__yise"] = "锁定技；当其他角色获得你的牌后，若此牌为：红色，你可以摸一张牌或令其回复1点体力；黑色，你可以令其下次受到【杀】造成的伤害时，此伤害+1。",
  ["joy__shunshi"] = "顺世",
  [":joy__shunshi"] = "准备阶段或当你于回合外受到伤害后，你可以交给一名其他角色一张牌，然后直到你获得以下效果：下个摸牌阶段多摸一张牌、"..
  "下个出牌阶段使用的【杀】次数上限+1且无视防具、下个弃牌阶段手牌上限+1。",
  ["#joy__yise-invoke1"] = "异色：你可以选择摸一张牌或令 %dest 回复1点体力",
  ["#joy__yise-invoke3"] = "异色：你可以令 %dest 下次受到【杀】造成的伤害时，伤害+1",
  ["joy__yiseDrawCard"] = "你摸一张牌",
  ["joy__yiseCover"] = "令其回复1点体力",
  ["joy__yisecancel"] = "取消",

  ["#joy__shunshi-cost"] = "顺世：你可以交给一名其他角色一张牌，然后你下个对应阶段获得对应效果",
  ["#joy__yise_delay"] = "异色",
  ["#joy__shunshi_delay"] = "顺世",
  ["@joy__yise"] = "异色",
  ["@joy__shunshi_drawcards"] = "摸牌阶段",
  ["@joy__shunshi_slash"] = "出牌阶段",
  ["@joy__shunshi_maxcard"] = "弃牌阶段",

}

local zhangchangpu = General(extension, "joy__zhangchangpu", "wei", 3, 3, General.Female)
Fk:addPoxiMethod{
  name = "joy__yanjiao_count",
  card_filter = function(to_select, selected,data,extra_data)
    local n = Fk:getCardById(to_select).number
    for _, id in ipairs(selected) do
      n = n + Fk:getCardById(id).number
    end
    return n <= extra_data//2
  end,
  feasible = function(selected)
    return #selected > 0
  end,
  prompt = function ()
    return Fk:translate("#joy__yanjiao-choose")
  end
}
local yanjiao = fk.CreateActiveSkill{
  name = "joy__yanjiao",
  anim_type = "support",
  card_num = 0,
  target_num = 1,
  prompt = "#joy__yanjiao",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local n = 3 + player:getMark("@joy__yanjiao")
    room:setPlayerMark(player, "@joy__yanjiao", 0)
    local cards = room:getNCards(n)
    room:moveCards({
      ids = cards,
      toArea = Card.Processing,
      moveReason = fk.ReasonJustMove,
      skillName = self.name,
    })
    local m = 0
    local i = 1
    for _, id in ipairs(cards) do
      local card = Fk:getCardById(id)
      m = m + Fk:getCardById(id).number
      room:addCardMark(card,"joy_yj-phase",m)
    end
    local get = room:askForPoxi(target, "joy__yanjiao_count", {{ self.name, cards}}, m, true)
    if #get > 0 then
      local dummy = Fk:cloneCard("dilu")
      dummy:addSubcards(get)
      room:obtainCard(target.id, dummy, true, fk.ReasonPrey)
    end
    cards = table.filter(cards, function(id) return room:getCardArea(id) == Card.Processing end)
    if target ~= player and not player.dead and #cards > 0 then
      local dummy2 = Fk:cloneCard("dilu")
      dummy2:addSubcards(cards)
      room:obtainCard(player.id, dummy2, true, fk.ReasonPrey)
    elseif target == player and #cards > 0 then
        room:moveCards({
          ids = cards,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonPutIntoDiscardPile,
        })
    end
  end,
}
local xingshen = fk.CreateTriggerSkill{
  name = "joy__xingshen",
  anim_type = "masochism",
  events = {fk.Damaged},
  on_use = function(self, event, target, player, data)
    local room = player.room
    if table.every(room.alive_players, function(p) return p:getHandcardNum() >= player:getHandcardNum() end) then
      player:drawCards(2, self.name)
    else
      player:drawCards(1, self.name)
    end
    if player.dead or player:getMark("@joy__yanjiao") > 5 then return end
    if table.every(room.alive_players, function(p) return p.hp >= player.hp end) then
      room:addPlayerMark(player, "@joy__yanjiao", player:getMark("@joy__yanjiao") > 3 and 1 or 2)
    else
      room:addPlayerMark(player, "@joy__yanjiao", 1)
    end
  end,
}
zhangchangpu:addSkill(yanjiao)
zhangchangpu:addSkill(xingshen)
Fk:loadTranslationTable{
  ["joy__zhangchangpu"] = "张昌蒲",
  ["#joy__zhangchangpu"] = "矜严明训",

  ["joy__yanjiao"] = "严教",
  [":joy__yanjiao"] = "出牌阶段限一次，你可以选择一名角色并亮出牌堆顶的三张牌，该角色选择并获得点数之和小于等于总点数一半的牌（至少获得一张），"..
  " 若〖严教〗目标不为你，你获得剩余的牌；若〖严教〗目标为你，则弃置剩余的牌。",
  ["joy__xingshen"] = "省身",
  [":joy__xingshen"] = "当你受到伤害后，你可以摸一张牌并令下一次发动〖严教〗亮出的牌数+1。若你的手牌数为全场最少，则改为摸两张牌；"..
  "若你的体力值为全场最少，则下一次发动〖严教〗亮出的牌数改为+2（加值总数至多为5）。",
  ["#joy__yanjiao"]= "严教：选择一名角色发动“严教”",
  ["#joy__yanjiao-choose"] = "严教：选择获得点数和小于总点数一半的牌",
  ["joy__yanjiao_count"] = "严教",
  ["@joy__yanjiao"] = "严教",
  
  ["$joy__yanjiao1"] = " ",
  ["$joy__yanjiao2"] = " ",
  ["$joy__xingshen1"] = " ",
  ["$joy__xingshen2"] = " ",
  ["~joy__zhangchangpu"] = " ",
}

local wenqin = General(extension, "joy__wenqin", "wei", 4)
wenqin:addSkill("guangao")
wenqin:addSkill("huiqi")
wenqin:addRelatedSkill("xieju")
Fk:loadTranslationTable{
  ["joy__wenqin"] = "文钦",
  ["#joy__wenqin"] = "困兽鸱张",
}

local lijue = General(extension, "joy__lijue", "qun", 5, 6)
lijue:addSkill("langxi")
lijue:addSkill("yisuan")
Fk:loadTranslationTable{
  ["joy__lijue"] = "李傕",
  ["#joy__lijue"] = "恐怖羊袭",
}

local liangxing = General(extension, "joy__liangxing", "qun", 4)
local lulue = fk.CreateTriggerSkill{
  name = "joy__lulue",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room:getOtherPlayers(player), function(p)
      return (p:getHandcardNum() <= #player.player_cards[Player.Hand] and not p:isKongcheng()) end), Util.IdMapper)
    if #targets == 0 then return end
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#joy__lulue-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
    return false
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data)
    local choice = room:askForChoice(to, {"lulue_give", "lulue_slash"}, self.name, "#lulue-choice:"..player.id)
    if choice == "lulue_give" then
      local dummy = Fk:cloneCard("dilu")
      dummy:addSubcards(to:getCardIds(Player.Hand))
      room:obtainCard(player.id, dummy, false, fk.ReasonGive)
      player:turnOver()
    else
      to:turnOver()
      room:useVirtualCard("slash", nil, to, player, self.name, true)
    end
  end,
}
liangxing:addSkill(lulue)
liangxing:addSkill("zhuixi")
Fk:loadTranslationTable{
  ["joy__liangxing"] = "梁兴",
  ["#joy__liangxing"] = "凶豺掠豹",

  ["joy__lulue"] = "掳掠",
  [":joy__lulue"] = "出牌阶段开始时，你可以令一名有手牌且手牌数小于等于你的其他角色选择一项：1.将所有手牌交给你，然后你翻面；2.翻面，然后视为对你使用一张【杀】。",
  ["#joy__lulue-choose"] = "掳掠：你可以令一名有手牌且手牌数小于等于你的其他角色选择一项",
}



local joy__zhaoxiang = General(extension, "joy__zhaoxiang", "shu", 4, 4, General.Female)
local joy__fuhan = fk.CreateTriggerSkill{
  name = "joy__fuhan",
  events = {fk.TurnStart},
  frequency = Skill.Limited,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:getMark("@meiying") > 0 and
      player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#joy__fuhan-invoke")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = player:getMark("@meiying")
    room:setPlayerMark(player, "@meiying", 0)
    player:drawCards(n, self.name)
    if player.dead then return end

    local generals = {"joyex__zhugeliang","joyex__zhaoyun","joyex__machao","joyex__huangyueying","joyex__guanyu","joy_mou__machao","joy_mou__huangzhong","joy_mou__liubei","joy_mou__zhaoyun","joyex__zhurong","joy__yangwan",
    "joy__yanyan","joyex__weiyan","joy__liushan","joy__zhugezhan","joy__jiangwei","joy__menghuo","joy__wolong","joy__maliang","joy__ganfuren","joy__guanyinping","joyex__sunqian","joyex__huangzhong","joyex__zhangfei","joy__xiahouba","joy__qinmi",
    "joysp__sunshangxiang","joysp__zhangfei", "joy__puyuan","joy__baosanniang","joy__guansuo","joy__guanping", "joy__xushu","joyex__liaohua","joy__zhangsong","joy__wuyi","joy__wolongfengchu","joyex__liubei",
    "nya__xingcai","nya__zhurong","joy__zhangyi",}
    if #generals == 0 then return false end
    generals = table.random(generals, math.max(4, #room.alive_players))

    local skills = {}
    local choices = {}
    for _, general_name in ipairs(generals) do
      local general = Fk.generals[general_name]
      local g_skills = {}
      for _, skill in ipairs(general.skills) do
        if not (table.contains({Skill.Limited, Skill.Wake, Skill.Quest}, skill.frequency) or skill.lordSkill) and
        (#skill.attachedKingdom == 0 or (table.contains(skill.attachedKingdom, "shu") and player.kingdom == "shu")) then
          table.insertIfNeed(g_skills, skill.name)
        end
      end
      for _, s_name in ipairs(general.other_skills) do
        local skill = Fk.skills[s_name]
        if not (table.contains({Skill.Limited, Skill.Wake, Skill.Quest}, skill.frequency) or skill.lordSkill) and
        (#skill.attachedKingdom == 0 or (table.contains(skill.attachedKingdom, "shu") and player.kingdom == "shu")) then
          table.insertIfNeed(g_skills, skill.name)
        end
      end
      table.insertIfNeed(skills, g_skills)
      if #choices == 0 and #g_skills > 0 then
        choices = {g_skills[1]}
      end
    end
    if #choices > 0 then
      local result = player.room:askForCustomDialog(player, self.name,
      "packages/tenyear/qml/ChooseGeneralSkillsBox.qml", {
        generals, skills, 1, 2, "#joy__fuhan-choice", false
      })
      if result ~= "" then
        choices = json.decode(result)
      end
      room:handleAddLoseSkills(player, table.concat(choices, "|"), nil)
    end

    if not player.dead and player:isWounded() and
    table.every(room.alive_players, function(p) return p.hp >= player.hp end) then
      room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    end
  end,
}
joy__zhaoxiang:addSkill("ty__fanghun")
joy__zhaoxiang:addSkill(joy__fuhan)
Fk:loadTranslationTable{
  ["joy__zhaoxiang"] = "赵襄",
  ["#joy__zhaoxiang"] = "拾梅鹊影",

  ["joy__fuhan"] = "扶汉",
  [":joy__fuhan"] = "限定技，回合开始时，若你有“梅影”标记，你可以移去所有“梅影”标记并摸等量的牌，然后从X张（X为存活人数且至少为4）蜀势力"..
  "武将牌中选择并获得至多两个技能（限定技、觉醒技、主公技除外）。若此时你是体力值最低的角色，你回复1点体力。"..
  '<br /><font color="red">（村：欢杀包特色，只会获得欢杀池内武将的技能）</font>',
  ["#joy__fuhan-invoke"] = "扶汉：你可以移去“梅影”标记，获得两个蜀势力武将的技能！",
  ["#joy__fuhan-choice"] = "扶汉：选择你要获得的至多2个技能",
}

local yangwan = General(extension, "joy__yangwan", "shu", 3, 3, General.Female)
local youyan = fk.CreateActiveSkill{
  name = "joy__youyan",
  anim_type = "control",
  min_card_num = 1,
  prompt = "#joy__youyan",
  can_use = function(self, player)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, to_select, selected)
    return Fk:currentRoom():getCardArea(to_select) ~= Card.PlayerEquip
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    player.room:throwCard(effect.cards,self.name,player,player)
  end,
}
local youyan_trigger = fk.CreateTriggerSkill{
  name = "#joy__youyan__trigger",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and (player.phase == Player.Play or player.phase == Player.Discard) and
      player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 then
      local suits = {"spade", "club", "heart", "diamond"}
      local can_invoked = false
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile and move.moveReason ~= fk.ReasonUse and move.moveReason ~= fk.ReasonResonpse then
          if move.from == player.id then
            for _, info in ipairs(move.moveInfo) do
              if info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip then
                table.removeOne(suits, Fk:getCardById(info.cardId):getSuitString())
                can_invoked = true
              end
            end
          else
            local room = player.room
            local parentPindianEvent = player.room.logic:getCurrentEvent():findParent(GameEvent.Pindian, true)
            if parentPindianEvent then
              local pindianData = parentPindianEvent.data[1]
              if pindianData.from == player then
                local leftFromCardIds = room:getSubcardsByRule(pindianData.fromCard)
                for _, info in ipairs(move.moveInfo) do
                  if info.fromArea == Card.Processing and table.contains(leftFromCardIds, info.cardId) then
                    table.removeOne(suits, Fk:getCardById(info.cardId):getSuitString())
                    can_invoked = true
                  end
                end
              end
              for toId, result in pairs(pindianData.results) do
                if player.id == toId then
                  local leftToCardIds = room:getSubcardsByRule(result.toCard)
                  for _, info in ipairs(move.moveInfo) do
                    if info.fromArea == Card.Processing and table.contains(leftToCardIds, info.cardId) then
                      table.removeOne(suits, Fk:getCardById(info.cardId):getSuitString())
                      can_invoked = true
                    end
                  end
                end
              end
            end
          end
        end
      end
      if can_invoked and #suits > 0 then
        self.cost_data = suits
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local suits = self.cost_data
    local cards = {}
    while #suits > 0 do
      local pattern = table.random(suits)
      table.removeOne(suits, pattern)
      table.insertTable(cards, room:getCardsFromPileByRule(".|.|"..pattern))
    end
    if #cards > 0 then
      room:moveCards({
        ids = cards,
        to = player.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonJustMove,
        proposer = player.id,
        skillName = self.name,
      })
    end
  end,
}
local zhuihuan = fk.CreateTriggerSkill{
  name = "joy__zhuihuan",
  anim_type = "defensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room.alive_players, Util.IdMapper), 1, 1, "#joy__zhuihuan-choose", self.name, true, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:addPlayerMark(player.room:getPlayerById(self.cost_data), self.name, 1)
  end,
}
local zhuihuan_delay = fk.CreateTriggerSkill{
  name = "#joy__zhuihuan_delay",
  anim_type = "offensive",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player.phase == Player.Start and player:getMark("joy__zhuihuan") ~= 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "joy__zhuihuan", 0)
    local mark = player:getTableMark("joy__zhuihuan_record")
    local targets = table.filter(room:getAlivePlayers(), function (p)
      return table.contains(mark, p.id)
    end)
    room:setPlayerMark(player, "joy__zhuihuan_record", 0)
    for _, p in ipairs(targets) do
      if player.dead then break end
      if not p.dead then
        if p.hp > player.hp then
          room:damage({
            from = player,
            to = p,
            damage = 2,
            damageType = fk.NormalDamage,
            skillName = "joy__zhuihuan"
          })
        else
          local cards = table.filter(p:getCardIds(Player.Hand), function (id)
            return not p:prohibitDiscard(Fk:getCardById(id))
          end)
          cards = table.random(cards, 2)
          if #cards > 0 then
            room:throwCard(cards, "joy__zhuihuan", p, p)
          end
        end
      end
    end
  end,

  refresh_events = {fk.Damaged},
  can_refresh = function(self, event, target, player, data)
    return player == target and player:getMark("joy__zhuihuan") ~= 0 and data.from
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    local mark = player:getTableMark("joy__zhuihuan_record")
    table.insert(mark, data.from.id)
    room:setPlayerMark(player, "joy__zhuihuan_record", mark)
  end,
}
youyan:addRelatedSkill(youyan_trigger)
zhuihuan:addRelatedSkill(zhuihuan_delay)
yangwan:addSkill(youyan)
yangwan:addSkill(zhuihuan)
Fk:loadTranslationTable{
  ["joy__yangwan"] = "杨婉",
  ["#joy__yangwan"] = "融沫之鲡",

  ["joy__youyan"] = "诱言",
  [":joy__youyan"] = "①出牌阶段限一次，你可以弃置任意张手牌<br>②你的回合内，当你的牌因使用或打出之外的方式进入弃牌堆后，你可以从牌堆中获得本次弃牌中没有的花色的牌各一张（出牌阶段、弃牌阶段各限一次）。",
  ["joy__zhuihuan"] = "追还",
  [":joy__zhuihuan"] = "结束阶段，你可以秘密选择一名角色。直到该角色的下个准备阶段，此期间内对其造成过伤害的角色："..
  "若体力值大于该角色，则受到其造成的2点伤害；若体力值小于等于该角色，则随机弃置两张手牌。",
  ["#joy__zhuihuan-choose"] = "追还：选择一名角色，直到其准备阶段，对此期间对其造成过伤害的角色造成伤害或弃牌",
  ["#joy__zhuihuan_delay"] = "追还",
  ["#joy__youyan__trigger"] = "诱言",
  ["#joy__youyan"] = "诱言：出牌阶段限一次，你可以弃置任意张手牌",

  ["$joy__youyan1"] = "诱言者，为人所不齿。",
  ["$joy__youyan2"] = "诱言之弊，不可不慎。",
  ["$joy__zhuihuan1"] = "伤人者，追而还之！",
  ["$joy__zhuihuan2"] = "追而还击，皆为因果。",
  ["~joy__yangwan"] = "遇人不淑……",
}

local tangji = General(extension, "joy__tangji", "qun", 3, 3, General.Female)
local joy__kangge = fk.CreateTriggerSkill{
  name = "joy__kangge",
  events = {fk.TurnStart, fk.AfterCardsMove, fk.EnterDying},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.TurnStart then
        return target == player
      elseif event == fk.AfterCardsMove then
        if player:getMark("joy__kangge_draw-turn") < 3 then
          local n = 0
          for _, move in ipairs(data) do
            if move.to and move.toArea == Card.PlayerHand and player.room:getPlayerById(move.to):getMark("@@joy__kangge") > 0
            and player.room:getPlayerById(move.to).phase == Player.NotActive then
              n = n + #move.moveInfo
            end
          end
          if n > 0 then
            self.cost_data = n
            return true
          end
        end
      else
        return target.dying and target:getMark("@@joy__kangge") > 0 and player:getMark("joy__kangge_help-round") == 0
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.EnterDying then
      return player.room:askForSkillInvoke(player, self.name, nil, "#joy__kangge-invoke::"..target.id)
    end
    return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event == fk.TurnStart then
      room:notifySkillInvoked(player, self.name, "special")
      local targets = table.map(room:getOtherPlayers(player), Util.IdMapper)
      if #targets == 0 then return end
      for _, p in ipairs(room:getOtherPlayers(player)) do
        if p:getMark("@@joy__kangge") > 0 then
          room:setPlayerMark(p, "@@joy__kangge", 0)
        end
      end
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#joy__kangge-choose", self.name, false)
      room:setPlayerMark(room:getPlayerById(tos[1]), "@@joy__kangge", 1)
    elseif event == fk.AfterCardsMove then
      room:notifySkillInvoked(player, self.name, "drawcard")
      local n = math.min(self.cost_data, 3 - player:getMark("joy__kangge_draw-turn"))
      room:addPlayerMark(player, "joy__kangge_draw-turn", n)
      player:drawCards(n, self.name)
    else
      room:notifySkillInvoked(player, "joy__kangge", "support")
      room:doIndicate(player.id, {target.id})
      room:setPlayerMark(player, "joy__kangge_help-round", 1)
      room:recover({
        who = target,
        num = 1 - target.hp,
        recoverBy = player,
        skillName = self.name,
      })
    end
  end,
}
local joy__jielie = fk.CreateTriggerSkill{
  name = "joy__jielie",
  anim_type = "defensive",
  events = {fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#joy__jielie-invoke")
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = table.filter(room:getOtherPlayers(player), function(p) return p:getMark("@@joy__kangge") > 0 end)[1]
    local suit
    if to then
      local suits = {"spade", "heart", "club", "diamond"}
      local choices = table.map(suits, function(s) return "log_"..s end)
      local choice = room:askForChoice(player, choices, self.name, "#joy__jielie-choice::"..to.id..":"..data.damage)
      suit = suits[table.indexOf(choices, choice)]
      room:doIndicate(player.id, {to.id})
    end
    room:loseHp(player, 1, self.name)
    if to and not to.dead then
      local cards = room:getCardsFromPileByRule(".|.|"..suit, data.damage, "discardPile")
      if #cards > 0 then
        room:moveCards({
          ids = cards,
          to = to.id,
          toArea = Card.PlayerHand,
          moveReason = fk.ReasonJustMove,
          proposer = player.id,
          skillName = self.name,
        })
      end
    end
    return true
  end,
}
tangji:addSkill(joy__kangge)
tangji:addSkill(joy__jielie)
Fk:loadTranslationTable{
  ["joy__tangji"] = "唐姬",
  ["joy__kangge"] = "抗歌",
  [":joy__kangge"] = "回合开始时，你令一名其他角色获得“抗歌”标记（若已有此标记则转移给其）：当该角色于其回合外获得手牌时，你摸等量的牌（每回合最多摸3张）；每轮限一次，当该角色进入濒死状态时，你可以令其将体力回复至1点。",
  ["joy__jielie"] = "节烈",
  [":joy__jielie"] = "当你受到伤害时，你可以防止此伤害并选择一种花色，然后你失去1点体力，令“抗歌”角色从弃牌堆中随机获得X张此花色的牌（X为伤害值）。",
  ["#joy__kangge-choose"] = "抗歌：请选择“抗歌”角色",
  ["@@joy__kangge"] = "抗歌",
  ["#joy__kangge-invoke"] = "抗歌：你可以令 %dest 回复体力至1",
  ["#joy__jielie-invoke"] = "节烈：你可以防止你受到的伤害并失去1点体力",
  ["#joy__jielie-choice"] = "节烈：选择一种花色，令“抗歌”角色 %dest 从弃牌堆获得%arg张此花色牌",
}


local yangxiu = General(extension, "joy__yangxiu", "wei", 3)
local jilei = fk.CreateTriggerSkill{
  name = "joy__jilei",
  anim_type = "masochism",
  events = {fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from and not data.from.dead
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#joy__jilei-invoke::"..data.from.id)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, {"basic", "trick", "equip"}, self.name)
    local cards
    if choice == "basic" then
      cards = room:getCardsFromPileByRule(".|.|.|.|.|basic")
    elseif choice == "trick" then
      cards = room:getCardsFromPileByRule(".|.|.|.|.|trick")
    elseif choice == "equip" then
      cards = room:getCardsFromPileByRule(".|.|.|.|.|equip")
    end
      if #cards > 0 and not player.dead then
        local get = cards[1]
        room:obtainCard(player, get, false, fk.ReasonDraw)
      end
    local mark = data.from:getMark("@joy__jilei")
    if mark == 0 then mark = {} end
    table.insertIfNeed(mark, choice .. "_char")
    room:setPlayerMark(data.from, "@joy__jilei", mark)
  end,

  refresh_events = {fk.TurnStart},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:getMark("@joy__jilei") ~= 0
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "@joy__jilei", 0)
  end,
}
local jilei_prohibit = fk.CreateProhibitSkill{
  name = "#joy__jilei_prohibit",
  prohibit_use = function(self, player, card)
    local mark = player:getMark("@joy__jilei")
    if type(mark) == "table" and table.contains(mark, card:getTypeString() .. "_char") then
      local subcards = card:isVirtual() and card.subcards or {card.id}
      return #subcards > 0 and table.every(subcards, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
  prohibit_response = function(self, player, card)
    local mark = player:getMark("@joy__jilei")
    if type(mark) == "table" and table.contains(mark, card:getTypeString() .. "_char") then
      local subcards = card:isVirtual() and card.subcards or {card.id}
      return #subcards > 0 and table.every(subcards, function(id)
        return table.contains(player:getCardIds(Player.Hand), id)
      end)
    end
  end,
  prohibit_discard = function(self, player, card)
    local mark = player:getMark("@joy__jilei")
    return type(mark) == "table" and table.contains(mark, card:getTypeString() .. "_char")
  end,
}
jilei:addRelatedSkill(jilei_prohibit)
yangxiu:addSkill("ty__danlao")
yangxiu:addSkill(jilei)
Fk:loadTranslationTable{
  ["joy__yangxiu"] = "杨修",
  ["#joy__yangxiu"] = "恃才放旷",

  ["joy__jilei"] = "鸡肋",
  [":joy__jilei"] = "当你受到伤害后，你可以声明一种牌的类别，然后获得一张该类别的牌，并令伤害来源不能使用、打出或弃置你声明的此类手牌直到其下回合开始。",
  ["#joy__jilei-invoke"] = "鸡肋：是否获得一张指定类别的牌，并令 %dest 不能使用、打出、弃置该类别牌直到其下回合开始？",
  ["@joy__jilei"] = "鸡肋",
}

local quyi = General(extension, "joy__quyi", "qun", 4)
local fuji = fk.CreateTriggerSkill{
  name = "joy__fuji",
  anim_type = "offensive",
  events = {fk.CardUsing},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      (data.card.trueName == "slash" or data.card:isCommonTrick()) and
      table.find(player.room:getOtherPlayers(player), function(p) return p:distanceTo(player) < 3 end)
  end,
  on_use = function(self, event, target, player, data)
    local targets = table.filter(player.room:getOtherPlayers(player), function(p) return p:distanceTo(player) <3 end)
    if #targets > 0 then
      data.disresponsiveList = data.disresponsiveList or {}
      for _, p in ipairs(targets) do
        table.insertIfNeed(data.disresponsiveList, p.id)
      end
    end
  end,
}
local fuji_mark = fk.CreateTriggerSkill{
  name = "#joy__fuji_mark",
  anim_type = "offensive",
  mute = true,
  events = {fk.Damaged},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
      return target ~= player and data.from == player and player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
      room:addPlayerMark(target, "@@joyfuji")
      room:addPlayerMark(target, MarkEnum.UncompulsoryInvalidity)
  end,
  refresh_events = { fk.TurnStart },
  can_refresh = function(self, event, target, player, data)
      return target ~= Player 
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(room:getAlivePlayers()) do
      if p:getMark("@@joyfuji") > 0 then
        room:removePlayerMark(p, "@@joyfuji")
        room:removePlayerMark(p,MarkEnum.UncompulsoryInvalidity)
      end
    end
  end,
}
local jiaozi = fk.CreateTriggerSkill{
  name = "joy__jiaozi",
  anim_type = "offensive",
  events = {fk.DamageCaused},
  frequency = Skill.Compulsory,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      table.every(player.room:getOtherPlayers(player), function(p)
        return player:getHandcardNum() >= p:getHandcardNum() end)
  end,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage + 1
  end,
}
fuji:addRelatedSkill(fuji_mark)
quyi:addSkill(fuji)
quyi:addSkill(jiaozi)
Fk:loadTranslationTable{
  ["joy__quyi"] = "麴义",
  ["#joy__quyi"] = "名门的骁将",

  ["joy__fuji"] = "伏骑",
  ["#joy__fuji_mark"] = "伏骑",
  [":joy__fuji"] = "锁定技，当你使用【杀】或普通锦囊牌时，你令所有至你距离为2的角色不能响应此牌。"..
  "且被你造成伤害的其他角色的非锁定技失效，其他角色的回合开始时解除",
  ["joy__jiaozi"] = "骄恣",
  [":joy__jiaozi"] = "锁定技，当你造成伤害时，若你的手牌为全场最多，则此伤害+1。",
  ["@@joyfuji"] = "伏骑",

  ["$joy__fuji1"] = " ",
  ["$joy__fuji2"] = " ",
  ["$joy__jiaozi1"] = " ",
  ["$joy__jiaozi2"] = " ",
  ["$~joy__quyi"] = " ",
}

local joy__sunhao = General(extension, "joy__sunhao", "wu", 5)
local joy__canshi = fk.CreateTriggerSkill{
  name = "joy__canshi",
  anim_type = "drawcard",
  events = {fk.DrawNCards},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and table.find(player.room.alive_players, function (p)
      return p:isWounded() or (player:hasSkill("joy__guiming") and p.kingdom == "wu" )
    end)
  end,
  on_cost = function (self, event, target, player, data)
    local n = 0
    for _, p in ipairs(player.room.alive_players) do
      if p:isWounded() or (player:hasSkill("joy__guiming") and p.kingdom == "wu" ) then
        n = n + 1
      end
    end
    if player.room:askForSkillInvoke(player, self.name, nil, "#joy__canshi-invoke:::"..n) then
      self.cost_data = n
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    data.n = data.n + self.cost_data
  end,
}
local joy__canshi_delay = fk.CreateTriggerSkill{
  name = "#joy__canshi_delay",
  anim_type = "negative",
  events = {fk.CardUsing},
  can_trigger = function(self, event, target, player, data)
    return target == player and data.card.trueName == "slash" and
      player:usedSkillTimes(joy__canshi.name) > 0 and not player:isNude()
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player.room:askForDiscard(player, 1, 1, true, self.name, false)
  end,
}
local joy__chouhai = fk.CreateTriggerSkill{
  name = "joy__chouhai",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events ={fk.DamageInflicted},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:isKongcheng() and #player:getCardIds("e") == 0 and data.card and data.card.trueName == "slash"
    
  end,
  on_use = function(self, event, target, player, data)
    data.damage = data.damage + 1
  end,
}
local guiming = fk.CreateTriggerSkill{
  name = "joy__guiming$",
  frequency = Skill.Compulsory,
}
joy__canshi:addRelatedSkill(joy__canshi_delay)
joy__sunhao:addSkill(joy__canshi)
joy__sunhao:addSkill(joy__chouhai)
joy__sunhao:addSkill(guiming)
Fk:loadTranslationTable{
  ["joy__sunhao"] = "孙皓",
  ["#joy__sunhao"] = "时日曷丧",

  ["joy__canshi"] = "残蚀",
  [":joy__canshi"] = "摸牌阶段，你可以多摸X张牌（X为已受伤的角色数），若如此做，当你于此回合内使用【杀】时，你弃置一张牌。",
  ["#joy__canshi_delay"] = "残蚀",
  ["joy__chouhai"] = "仇海",
  [":joy__chouhai"] = "锁定技，当你受到【杀】造成的伤害时，若你没有手牌和装备，此伤害+1。",
  ["#joy__canshi-invoke"] = "残蚀：你可以多摸 %arg 张牌",

  ["joy__guiming"] = "归命",
  [":joy__guiming"] = "主公技，锁定技，吴势力角色于你的回合内视为已受伤的角色。",

}
return extension